<?php

namespace App\Services\Account;

use App\Models\Account\UserAccountGroupModel;
use App\Models\Account\UserAccountModel;
use App\Models\Account\UserAccountSkuModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Models\Assess\OrderAndCustomersOrderModel;
use App\Models\User;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\RedisService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserAccountService extends BaseService
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new UserAccountModel();
    }

    /**
     * @Notes:获取用户与账号管理信息
     * @Interface getList
     * @return array
     * @author: wuyu
     * @Time: 2023/6/2   19:10
     */
    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map = [];
        $user = getter($param, 'user', 0);
        $userGroupId = getter($param, 'user_group_id', 0);
        $account = getter($param, 'account', '');
        $sort = getter($param, 'sort', 'id');
        $order = getter($param, 'order', 'desc');

        if (!empty($user)) $map[] = ['user_id', '=', $user];
        if (!empty($userGroupId)) $map[] = ['user_group_id', '=', $userGroupId];
        if (!empty($account)) $map[] = ['account_name', '=', $account];

        //权限过滤
        $userIdRule = $this->model->userId;
        if (!empty($userIdRule) && !in_array($userIdRule,$this->model->userAllIds)) $map[] = ['user_id', '=', $userIdRule];

        $list = $this->model->getList($map, [[$sort, $order]]);

        $UserAccountSkuModel = new UserAccountSkuModel();
        $UserModel = new UserModel();
        $skuArr = [];
        $userArr = [];
        if (!empty($list)){
            $ids = array_column($list,'id');
            $userGroupId = array_column($list,'user_group_id');
            $skuList = $UserAccountSkuModel->whereIn('user_account_id',$ids)->get()->toArray();
            $userList = $UserModel->whereIn('id',$userGroupId)->get(['id','username'])->toArray();
            $userArr = array_column($userList,'username','id');
            foreach ($skuList as $v2){
                $skuArr[$v2['user_account_id']][] = $v2;
            }
        }

        foreach ($list as $key=>$val){

            $val['user_ids'] = [];
            $val['platform_sku_html'] = '';
            $val['user_group_id_html'] = $userArr[$val['user_group_id']]??'';

            if (!empty($skuArr[$val['id']])){
                $val['platform_sku_select'] = array_column($skuArr[$val['id']],'sku');
                $val['platform_sku_html'] = implode(';',$val['platform_sku_select']);
            }

            $list[$key] = $val;
        }

        return message("操作成功", true, $list);

    }


    /**
     * @Notes:获取用户与账号管理配置
     * @Interface getUserAccountConfig
     * @author: wuyu
     * @Time: 2023/6/2   17:54
     */
    public function getUserAccountConfig()
    {
        $config = [];
        //获取用户信息
        $userData = RedisService::getUserAccountList();
        $config['user_list'] = $userData;
        //获取店铺名
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $config['account_list'] = $OrderAndCustomersOrderModel->groupBy(['user_account','platform_user_name'])->get(['user_account','platform_user_name'])->toArray();
        $config['auth_sku_all'] = 1;
        //获取平台sku
        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        //管理者可以开设所有sku
        if (in_array($this->model->userId,$this->model->userAllIds)){
            $platformSkuList = $OrderAndCustomersOrderDetailModel->limit(200)->groupBy(['platform_sku'])->get(['platform_sku'])->toArray();
        }else{
            //获取主管下面的sku
            $UserAccountModel = new UserAccountModel();
            $UserAccountSkuModel = new UserAccountSkuModel();
            $accountData = $UserAccountModel->getOne([
                ['user_group_id','=',$this->model->userId]
            ]);
            if (!empty($accountData)){
                $accountGroup = $UserAccountModel->getOne([
                    ['user_group_id','=',$accountData['user_id']],
                    ['user_id','=',$accountData['user_id']],
                ]);
                if (!empty($accountGroup)){
                    $skuData = $UserAccountSkuModel->where('user_account_id','=',$accountGroup['id'])->get()->toArray();
                    $skus = array_column($skuData,'sku');
                    $platformSkuList = [];
                    if (!empty($skus)) $platformSkuList = $OrderAndCustomersOrderDetailModel->whereIn('platform_sku',$skus)->groupBy(['platform_sku'])->get(['platform_sku'])->toArray();
                }
            }
            $config['auth_sku_all'] = 0;
        }

        $config['platform_sku_list'] = array_column($platformSkuList,'platform_sku');

        return message("获取成功", true,$config);
    }

    /**
     * @Notes:添加或编辑
     * @Interface edit
     * @return array|void
     * @author: wuyu
     * @Time: 2023/5/8   16:45
     */
    public function edit()
    {
        try {
            DB::connection($this->model->connection)->beginTransaction(); //开启事务
            $params = request()->all();
            $id = $params['id'] ?? 0;
//            $accountName = $params['account_name'] ?? '';
            $platformSkuSelect = $params['platform_sku_select'] ?? [];
            $userGroupId = $params['user_group_id'] ?? '';
            $status = $params['status'] ?? 1;
            $userId = $params['user_id'] ?? 0;

//            if (empty($accountName)) throw new \Exception('账号不能为空');
            if (empty($status)) throw new \Exception('状态不能为空');
            if (empty($userId)) throw new \Exception('用户不能为空');

            $data = [
//                'account_name' => $accountName,
                'user_id' => $userId,
                'user_group_id' => $userGroupId
            ];
            $exists = $this->model->getOne([
//                ['account_name', '=', $accountName],
//                ['user_id', '=', $userId],
                ['user_group_id', '=', $userGroupId],

            ]);
            if (!empty($exists) && empty($id)){
                throw new \Exception('用户分组管理已存在,请勿重复添加');
            }elseif (!empty($exists) && $exists['id'] != $id){
                throw new \Exception('用户分组管理已存在,请勿重复添加');
            }
            $UserModel = new UserModel();
//            $UserAccountGroupModel = new UserAccountGroupModel();
            $UserAccountSkuModel = new UserAccountSkuModel();
            $userData = $UserModel->getOne([
                ['id','=',$userId]
            ],'id,username');
            $data['user_name'] = $userData['username'];

            $userIdsCol = [];
//            if (!empty($userIds)){
//                $userIdsList = $UserModel->whereIn('id',$userIds)->get(['id','realname'])->toArray();
//                $userIdsCol = array_column($userIdsList,'realname','id');
//            }

            //获取店铺名
            $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
//            $platformUserName= $OrderAndCustomersOrderModel->getOne([
//                ['user_account','=',$accountName]
//            ],'platform_user_name');
//            $data['account_abbr'] = $platformUserName['platform_user_name'] ?? '';

            if (empty($id)) {
                $data['create_user'] = $this->model->userId;
                $data['update_time'] = time();
                $data['create_time'] = time();
                $id = $this->model->insertGetId($data);
            } else {
                $data['update_user'] = $this->model->userId;
                $data['update_time'] = time();
                $this->model->where('id', '=', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            }
            if (empty($id)) throw new \Exception('操作失败');

            //删除用户组员
//            $UserAccountGroupModel->where('user_account_id','=',$id)->delete();
//            foreach ($userIds as $val){
//                $groupData = [
//                    'user_account_id'=>$id,
//                    'user_group_id'=>$val,
//                    'user_name'=>$userIdsCol[$val] ?? ''
//                ];
//                $UserAccountGroupModel->insert($groupData);
//            }

            //删除sku
            $UserAccountSkuModel->where('user_account_id','=',$id)->delete();
            foreach ($platformSkuSelect as $vv){
                $skuData = [
                    'user_account_id'=>$id,
                    'sku'=>$vv
                ];
                $UserAccountSkuModel->insert($skuData);
            }

            DB::connection($this->model->connection)->commit(); //事务提交
            return message("保存成功", true, []);

        } catch (\Exception $e) {
            DB::connection($this->model->connection)->rollBack(); //事务回滚
            return message("保存失败:" . $e->getMessage(), false, []);
        }
    }

    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }


}
